package demo.task;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.common.utils.NamedThreadFactory;

/**
 * 定时任务，用于将审批过的案件提交到WS
 * 
 * @author hanjy
 *
 */
@Component
public class TimerTaskDemo  implements DisposableBean  {

    private Logger logger = LoggerFactory.getLogger(TimerTaskDemo.class);

    private static long delay = 1000;

    private static ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1,
            new NamedThreadFactory("Monitor", true));

    @PostConstruct
    public void startTask() {
        logger.info("start Task.");

        executor.scheduleAtFixedRate(() -> {
            printLog();
        }, delay, delay, TimeUnit.SECONDS);

        executor.scheduleWithFixedDelay(() -> {
            printLog();
        }, delay, delay, TimeUnit.SECONDS);
    }

    @PreDestroy
    public void stopTask() {
        logger.info("@PreDestroy");
        executor.shutdown();
    }

    void printLog() {
        logger.trace("----------------------trace----------------------");
        logger.debug("----------------------debug----------------------");
        logger.info("----------------------info----------------------");
        logger.warn("----------------------warn----------------------");
        logger.error("----------------------error----------------------");
    }

    @Override
    public void destroy() throws Exception {
        logger.info("destroy");
        executor.shutdown();
    }

}
